package com.liugai.lgeachday.tool;

import com.liugai.lgeachday.request.Response;
import com.liugai.tool.encrypt.Encrypter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Component
public class FileHandler {

    @Value("${upload-path}")
    private String fileHoldePath;

    @Value("${file-host}")
    private String fileHost;

    public Response uploadImage(MultipartFile file) {
        String url = saveFile(file);
        Response response = new Response(200,null,url);
        return response;
    }

    public Response uploadImages(List<MultipartFile> files) {
        if (files == null || files.isEmpty()) {
            System.out.println("文件为空空");
        }
        List<String> list = new ArrayList<>();
        for(MultipartFile file: files) {
            String url = saveFile(file);
            if (url == null) {
                break;
            }
            list.add(url);
        }
        if (list.size() != files.size()) {
            return Response.failedResponse("图片部分上传失败，需重新上传");
        }
        Response response = new Response(200,null,list);
        return response;
    }

    private String saveFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return null;
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = fileHoldePath; // 上传后的路径
        fileName = Encrypter.md5(UUID.randomUUID()+"") + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String fileUrl = fileHost+'/'+fileName;
        return fileUrl;
    }

    public String getFileHoldePath() {
        return fileHoldePath;
    }

    public String getFileHost() {
        return fileHost;
    }

    @Override
    public String toString() {
        return "FileHandler{" +
                "fileHoldePath='" + fileHoldePath + '\'' +
                ", fileHost='" + fileHost + '\'' +
                '}';
    }
}
